import tkinter as tk
from tkinter import ttk
from src.globals import g_ic_debugger
import os
import json


class Config_show_lib(tk.Frame):
    def __init__(self, master, rooter):
        super().__init__(master=master)
        self.ROOTER = rooter

        self.view_init()

    def view_init(self):
        self.frame1_r1c1 = tk.LabelFrame(self, text="frame1_r1c1")
        self.frame1_r1c1.grid(row=1, column=1)

        self.frame1_r1c1_init()

        self.frame2_r2c1 = tk.LabelFrame(self, text="frame2_r2c1")
        self.frame2_r2c1.grid(row=2, column=1)

        self.frame2_r2c1_init()

    def frame1_r1c1_init(self):
        self.frame1_Btns = {}
        self.frame1_Functions = {}

        COLUMN = 6
        i = 0

        # 遍历config文件夹下的所有json文件
        for root, dirs, files in os.walk("./config"):
            # g_ic_debugger(root, dirs)

            for file in files:
                if file.endswith(".json"):
                    file_path = os.path.join(root, file)
                    row = i // COLUMN
                    column = i % COLUMN
                    # g_ic_debugger(file_path, row, column)
                    i += 1

                    self.frame1_Btns[f'{row}{column}'] = tk.Button(
                        self.frame1_r1c1, text=file, command=self.traversal_config(file_path))
                    self.frame1_Btns[f'{row}{column}'].grid(
                        row=row, column=column)

    def traversal_config(self, file_path):
        from src.utils.treeview_show_json import populate_treeview

        def wrapper():
            toplevel = tk.Toplevel(master=self, width=600, height=500)
            treeview = ttk.Treeview(
                toplevel, show="tree", height=25)
            # 设置treeview的宽度，没有找到好方法，临时设置一个列宽来实现
            treeview.column("#0", width=600)
            treeview.pack()
            with open(file_path, "r", encoding='utf-8') as f:
                config_data = json.load(f)

                populate_treeview(tree=treeview, node=config_data)

        return wrapper

    def frame2_r2c1_init(self):
        g_ic_debugger("r2c1_init")
        pass
